package com.panfeng.xcloud.boss.provider.member.service.impl;

import com.panfeng.xcloud.boss.provider.member.constants.LockContants;
import com.panfeng.xcloud.boss.provider.member.dao.mapper.*;
import com.panfeng.xcloud.boss.provider.member.lock.DistributedRedisLock;
import com.panfeng.xcloud.boss.provider.member.lock.RedisLock;
import com.panfeng.xcloud.boss.provider.member.service.IUserFamilyOptService;
import com.panfeng.xcloud.common.core.constants.BlConstants;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.exceptions.BaseBizException;
import com.panfeng.xcloud.dao.member.entity.UserBase;
import com.panfeng.xcloud.dao.member.entity.UserFamilyTree;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class UserFamilyOptServiceImpl implements IUserFamilyOptService {

    @Resource
    private UserFamilyTreeMapperExt userFamilyTreeMapperExt;

    @Resource
    private UserBaseMapperExt userBaseMapperExt;

    @Resource
    private UserActiveMapperExt userActiveMapperExt;

    @Resource
    private UserMaxActiveMapperExt userMaxActiveMapperExt;

    @Resource
    private UserActiveHistoryMapperExt userActiveHistoryMapperExt;

    @Autowired
    private RedisLock redisLock;

    /**
     * 异步建立用户邀请关系族谱
     *
     * @param userId
     * @param inviteCode
     */
    @Override
    public void asynBuildUserFamilyInfo(String userId, String inviteCode) {
        CompletableFuture.runAsync(()->{
            log.info(">>> 开始建立用户邀请关系树-家族图谱关系,当前用户userId：{}，上级邀请人userId（邀请码）：{} <<<",userId,inviteCode);
            if(BlConstants.INVITATION_CODE.equals(inviteCode)){
                log.info(">>>> 建立用户邀请关系树-家族图谱关系时邀请码为内部邀请码,当前用户userId：{}，上级邀请人userId（邀请码）：{} <<<",userId ,inviteCode);
            }
            String lockKey = LockContants.XDCLOUD_LOCK_TASK_ASYNBUILDUSERFAMILY + inviteCode;
            DistributedRedisLock.lock(lockKey);
            try{
                if(StringUtils.isNotBlank(inviteCode)){
                    if(!inviteCode.equals(BlConstants.INVITATION_CODE)){
                        UserBase inviteUser = userBaseMapperExt.queryUserInfo(inviteCode);
                        if(inviteUser == null){
                            log.info(">>> 建立用户邀请关系树-家族图谱关系时，校验邀请码非平台合法用户，当前用户userId：{}，上级邀请人userId（邀请码）：{}<<<<",userId ,inviteCode);
                            throw new BaseBizException(ResponseStatusEnum.INVITE_CODE_ERROR);
                        }
                        //查询邀请码对应用户的族谱
                        List<UserFamilyTree> userFamilyTreeList = userFamilyTreeMapperExt.selectUserFamilyInfoByUserId(inviteCode);
                        if(null == userFamilyTreeList || userFamilyTreeList.isEmpty()){
                            log.info(">>> 建立用户邀请关系树-家族图谱关系时，当前邀请人的族谱列表信息不存在，当前用户userId：{}，上级邀请人userId（邀请码）：{}<<<<",userId ,inviteCode);
                            throw new BaseBizException(ResponseStatusEnum.USERFAMILYTREE_LIST_IS_EMPTY_ERROR);
                        }
                        //邀请用户族谱
                        UserFamilyTree inviteUserFamilyTree = userFamilyTreeMapperExt.selectCurrentUserFromUserFamily(inviteCode);
                        if(null == inviteUserFamilyTree){
                            log.info(">>> 建立用户邀请关系树-家族图谱关系时，当前邀请人在族谱中不存在，当前用户userId：{}，上级邀请人userId（邀请码）：{}<<<<",userId ,inviteCode);
                            throw new BaseBizException(ResponseStatusEnum.USERFAMILYTREE_IS_NOT_EXIST_ERROR);
                        }
                        List<UserFamilyTree> oneLevelChild = userFamilyTreeMapperExt.selectOneLevelChildsByUserIdAndLevel(inviteCode,inviteUserFamilyTree.getUserNodeLevel() + 1);
                        int oneLevelChildNum = null != oneLevelChild || !oneLevelChild.isEmpty() ? oneLevelChild.size() : 0;
                        log.info(">>> 建立用户邀请关系树-家族图谱关系时，当前邀请好友的一级好友数量为：{} <<< ",oneLevelChildNum);
                        List<UserFamilyTree> insertFamilyTreeList = new ArrayList<>();

                        //构建上级族谱信息
                        for (UserFamilyTree userFamilyTree : userFamilyTreeList){
                            UserFamilyTree userFamilyTreeTmp = new UserFamilyTree();

                            userFamilyTreeTmp.setUserId(userId);
                            userFamilyTreeTmp.setUserNodeLevel(inviteUserFamilyTree.getUserNodeLevel() + 1);
                            userFamilyTreeTmp.setUserChildNumber(oneLevelChildNum + 1);
                            userFamilyTreeTmp.setCreateTime(new Date());
                            userFamilyTreeTmp.setUpdateTime(new Date());
                            userFamilyTreeTmp.setMemberUserId(userFamilyTree.getMemberUserId());
                            userFamilyTreeTmp.setMemberNodeLevel(userFamilyTree.getMemberNodeLevel());
                            userFamilyTreeTmp.setMemberChildNumber(userFamilyTree.getMemberChildNumber());

                            insertFamilyTreeList.add(userFamilyTreeTmp);
                        }

                        //构建当前用户
                        UserFamilyTree currentUserFamilyTreeTmp = new UserFamilyTree();

                        currentUserFamilyTreeTmp.setUserId(userId);
                        currentUserFamilyTreeTmp.setUserNodeLevel(inviteUserFamilyTree.getUserNodeLevel() + 1);
                        currentUserFamilyTreeTmp.setUserChildNumber(oneLevelChildNum + 1);
                        currentUserFamilyTreeTmp.setCreateTime(new Date());
                        currentUserFamilyTreeTmp.setUpdateTime(new Date());
                        currentUserFamilyTreeTmp.setMemberUserId(userId);
                        currentUserFamilyTreeTmp.setMemberNodeLevel(inviteUserFamilyTree.getUserNodeLevel() + 1);
                        currentUserFamilyTreeTmp.setMemberChildNumber(oneLevelChildNum + 1);

                        insertFamilyTreeList.add(currentUserFamilyTreeTmp);

                        //批量插入族谱信息
                        int rs = userFamilyTreeMapperExt.batchInertUserFamilyInfo(insertFamilyTreeList);
                        if(rs > 0){
                            log.info(">>> 批量插入族谱成功 <<<");
                        }else{
                            log.info(">>> 批量插入族谱失败 <<<");
                        }
                    }else{
                        //说明上级邀请好友为平台内部顶级邀请码
                        List<UserFamilyTree> oneLevelChild = userFamilyTreeMapperExt.selectOneLevelChildsByInnerInviteCode();
                        int oneLevelChildNum = null != oneLevelChild || !oneLevelChild.isEmpty() ? oneLevelChild.size() : 0;
                        log.info(">>> 建立用户邀请关系树-家族图谱关系时，当前邀请好友的一级好友数量为：{} <<< ",oneLevelChildNum);

                        //构建当前用户
                        UserFamilyTree currentUserFamilyTreeTmp = new UserFamilyTree();

                        currentUserFamilyTreeTmp.setUserId(userId);
                        currentUserFamilyTreeTmp.setUserNodeLevel(1);
                        currentUserFamilyTreeTmp.setUserChildNumber(oneLevelChildNum + 1);
                        currentUserFamilyTreeTmp.setCreateTime(new Date());
                        currentUserFamilyTreeTmp.setUpdateTime(new Date());
                        currentUserFamilyTreeTmp.setMemberUserId(userId);
                        currentUserFamilyTreeTmp.setMemberNodeLevel(1);
                        currentUserFamilyTreeTmp.setMemberChildNumber(oneLevelChildNum + 1);

                        int rs = userFamilyTreeMapperExt.insertSelective(currentUserFamilyTreeTmp);

                        if(rs > 0){
                            log.info(">>> 插入族谱成功 <<<");
                        }else{
                            log.info(">>> 插入族谱失败 <<<");
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error(">>> asynBuildUserFamilyInfo-加锁创建族谱树异常", e);
            }finally {
                //TODO: 释放锁
                DistributedRedisLock.unlock(lockKey);
            }
        });
    }

}
